using System;
using System.Collections;
using System.Web;
using log4net.Appender;
using log4net.Core;

namespace Sedna.Core.Log
{
	public class InMemoryAppender : AppenderSkeleton
	{
		private ArrayList events = new ArrayList();

		public static readonly string KEY = "Sedna.InMemoryAppender";

		private static int RETENTION_AMOUNT = 20000;
		private static int RETENTION_THRESHOLD = (int)(RETENTION_AMOUNT * 1.2);

		public InMemoryAppender()
		{
			HttpContext.Current.Application[KEY] = this;
		}

		protected override void Append(LoggingEvent loggingEvent)
		{
			lock(events)
			{
				if(events.Count > RETENTION_THRESHOLD)
				{
					events.RemoveRange(RETENTION_AMOUNT - 1, events.Count - RETENTION_AMOUNT);
				}
				events.Add(loggingEvent);
			}
		}

		public IList EventsReversed
		{
			get
			{
				ArrayList cloned;
				lock(events)
				{
					cloned = events.Clone() as ArrayList;
				}
				cloned.Reverse();
				return cloned;
			}
		}

		public static InMemoryAppender Instance
		{
			get
			{
				return HttpContext.Current.Application[KEY] as InMemoryAppender;
			}
		}

	}
}
